package com.itchu.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itchu.common.domain.PageResult;
import com.itchu.common.exption.ExceptionEnum;
import com.itchu.common.exption.MusicException;
import com.itchu.system.domain.Category;
import com.itchu.system.domain.Singer;
import com.itchu.system.domain.Song;
import com.itchu.system.domain.SongList;
import com.itchu.system.mapper.CategoryMapper;
import com.itchu.system.mapper.SingerMapper;
import com.itchu.system.mapper.SongListMapper;
import com.itchu.system.service.SongListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class SongListServiceImpl implements SongListService {

    @Autowired
    private SongListMapper songListMapper;
    @Autowired
    private SingerMapper singerMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 查找歌单的分页信息
     * @param key   搜索条件
     * @param page  当前页
     * @param rows  页大小
     * @param sortBy
     * @param desc
     * @return
     */
    @Override
    public PageResult<SongList> findByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //开启分页
        PageHelper.startPage(page,rows);
        //创建一个封装条件的对象
        Example example = new Example(SongList.class);
        if (!StringUtils.isEmpty(key)) {
            Example.Criteria criteria = example.createCriteria();
            criteria.orLike("name","%" + key + "%");
            criteria.orLike("id","%" + key + "%");
        }
        if (!StringUtils.isEmpty(sortBy)) {
            example.setOrderByClause(sortBy+" "+(desc ? "desc" : "asc"));
        }
        List<SongList> songLists = songListMapper.selectByExample(example);
        PageInfo<SongList> pageInfo = new PageInfo<>(songLists);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(),songLists);
    }

    /**
     * 添加歌单操作
     * @param songList  歌单对象
     * @param cids   分类ids
     * @return
     */
    @Override
    public void addSongList(SongList songList, List<Long> cids) {
        if (songList != null) {
            songList.setCreateTime(new Date());
            songList.setUpdateTime(new Date());
            songList.setCount(0L);
            songListMapper.insertSelective(songList);
        }
        Long id = songList.getId();
        //2.向歌曲-分类表这个中间表添加记录
        songListMapper.delSongListIdAndCategoryIdBySid(id);
        songListMapper.addSongListIdAndCategoryId(id,cids);
    }

    /**
     * 修改歌单操作
     * @param songList  歌单对象
     * @param cids   分类ids
     * @return
     */
    @Override
    public void updateSongList(SongList songList, List<Long> cids) {
        if (songList != null) {
            //2.向歌曲-分类表这个中间表添加记录
            Long id = songList.getId();
            songListMapper.delSongListIdAndCategoryIdBySid(id);
            songListMapper.addSongListIdAndCategoryId(id,cids);

            songList.setUpdateTime(new Date());
            songListMapper.updateByPrimaryKey(songList);
        }
    }

    /**
     * 删除歌单操作
     * @param id  歌单id
     * @return
     */
    @Override
    public void deletSongList(Long id) {

        songListMapper.delSongListIdAndCategoryIdBySid(id);
        songListMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据歌单的id查找歌曲列表信息
     * @param id  歌单id
     * @return
     */
    @Override
    public List<Song> findListSongByLid(Long id) {
        List<Song> list = songListMapper.findListSongByLid(id);
        List<Singer> singers = singerMapper.selectAll();
        list.stream().forEach(song -> {
            singers.stream().forEach(singer -> {
                if (song.getSingerId().equals(singer.getId())) {
                    song.setSinger(singer);
                }
            });
        });
        return list;
    }

    /**
     * 给歌单添加歌曲操作
     * @param id  歌单id
     * @param sids   歌曲ids
     * @return
     */
    @Override
    public void addSongToList(Long id, List<Long> sids) {
        if (!CollectionUtils.isEmpty(sids)) {
            songListMapper.delSongListIdAndSongIdById(id);
            songListMapper.addSongToList(id,sids);
        }
    }

    /**
     * 在歌单列表删除多个歌曲
     * @param id  歌单id
     * @param sids  歌曲ids
     * @return
     */
    @Override
    public void deleteMutipleSong(Long id, List<Long> sids) {
        songListMapper.deleteMutipleSong(id,sids);
    }

    /**
     * 在歌单列表删除单个歌曲
     * @param id  歌单id
     * @param sid  歌曲id
     * @return
     */
    @Override
    public void deleteSong(Long id, Long sid) {
        songListMapper.deleteSong(id,sid);
    }

    /**
     * 根据分类的id查找歌单列表
     * @param page     当前页
     * @param rows     页大小
     * @param cid      分类id
     * @param isParent  是否是一级分类
     * @return
     */
    @Override
    public PageResult<SongList> findSongListByCategoryId(Integer page, Integer rows, Long cid, Long isParent) {
        // 1.开启分页
        PageHelper.startPage(page,rows);

        // 2.首先判断是否是一级分类，如果是一级分类，则查出所有的分类ids，根据分类Ids去找歌单
        //   如果不是一级分类则直接拿id查歌单
        List<SongList> list = null;
        if (isParent.equals(1L)) {
            Category record = new Category();
            record.setParentId(cid);
            List<Category> categoryList = categoryMapper.select(record);

            // 获得cids
            List<Long> cids = categoryList.stream()
                    .map(category -> category.getId())
                    .collect(Collectors.toList());
            // 如果该一级分类没有二级分类，则抛出异常，否则cids为空，则动态sql没有约束条件，会把所有歌曲查出来
            if (CollectionUtils.isEmpty(cids)) {
                throw new MusicException(ExceptionEnum.MUSIC_NOT_CHILDCATEGORY);
            }
            // 根据ids去查找歌单
            list = songListMapper.findListSongByCids(cids);
        }else {
            list = songListMapper.findListSongByCid(cid);
        }

        if (CollectionUtils.isEmpty(list)) {
            throw new MusicException(ExceptionEnum.MUSIC_NOT_SONGLISTCATEGORY);
        }

        PageInfo<SongList> pageInfo = new PageInfo<>(list);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(),list);
    }


    /**
     * 按名字做模糊搜索
     * @param name
     * @return
     */
    @Override
    public List<SongList> searchSongListsByName(String name) {
        Example example = new Example(SongList.class);
        example.createCriteria().andLike("title","%"+name+"%");
        List<SongList> list = songListMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(list)) {
            throw new MusicException(ExceptionEnum.MUSIC_NOT_SONGS);
        }
        return list;
    }
}